<?php
/**
 * @package html
 */
require_once '_dbobject.php';
require_once '_localemanager.php';
require_once '_img.php';
require_once '_system.php';
require_once '_stringex.php';
require_once '_htmlbase.php';

/**
 * Class which encapsulates view of offers in the thumbnail view.
 */
class HtmlOfferThumbnail extends HtmlOfferBase {
	/**
	 * @see HtmlBase::fetchInstance
	 * @return HtmlOfferList
	 */
	static function fetchInstance(resource $resource) {
		try {
			return new HtmlOfferThumbnail($resource);
		} catch(ExceptionResourceEmpty $e) {
			return false;
		}
	}
	// TODO alt in img and more .. more ..
	/**
	 * Beginning of html code.
	 */
	const HTML_BEGIN = '
		<!--<div class="offer-thumb-wrapper">-->
			<ul class="offer-thumb">
			    <li class="caption">
			    	<div style="height: 13px;">
			    		<span class="left"><img src="/img/3dotTop.png" alt="dot" /></span>
						<p> <a class="light" href="_TEMPLATE_OFFERHREF_">_TEMPLATE_TITLE_</a></p>
						<span class="right"><img src="/img/3dotTop.png" alt="dot" /></span>
						<span class="cleaner"></span>
					</div>
			    </li>
				<li class="pic">
					<div class="swc0"><div class="swc1">
						<div class="swc2">
							<a href="_TEMPLATE_OFFERHREF_">
								<img id="_TEMPLATE_FULLPICID_" class="pic" src="_TEMPLATE_FULLPICSRC_" alt="" />
							</a>
						</div>
						<span class="swc3" />
					</div></div>
				</li>
				<li class="description">
		            <p>
		            	_TEMPLATE_TEXT_
					</p>
					<div>
						_TEMPLATE_CHECKBOX_
					</div>
					<div style="cleaner"></div>
				</li>
				<li class="footer">
					<dl>
						<dt>
							<span class="left">
								_TEMPLATECODE_PRICE_: _TEMPLATE_PRICE_
							</span>
							<span class="right">
								<a class="light" href="_TEMPLATE_OFFERHREF_">
									_TEMPLATECODE_MORE_
								</a>
							</span>
							<span class="cleaner"></span>
						</dt>
						
						<dd>';
	
	/**
	 * Html code of one thumbnail.
	 */
	const HTML_THUMBNAIL = '
							<div class="thumbwrapped_TEMPLATE_THUMBCLASS_"> 
								<div class="swc0"><div class="swc1">
									<div class="swc2"> 
										<a href="#" onclick="javascript:Common.show(\'_TEMPLATE_FULLPICFULLNAME_\',\'_TEMPLATE_FULLPICID_\'); return false;" >
											<img src="_TEMPLATE_THUMBSRC_" alt="" />
										</a>
									</div>
									<span class="swc3"/>
								</div></div>
							</div>';
	
	/**
	 * Ending of html code.
	 */
	const HTML_END = '
							<div class="cleaner" ></div>
						</dd>
					</dl>
				</li>
			</ul>
		<!--</div>-->';
	
	/**
	 * Maximum count of minithumb in one thumbnail
	 */
	const THUMB_MAX = 8;
	
	/**
	 * Generate html code, but don't outpu it yet.
	 * @see HtmlObject::processMe
	 */
	public function processMe() {
		$info = SiteContext::getSiteContext();
		// Unrepeated html code.
		$this->buffer = self::HTML_BEGIN;
		
		for ($i = 0; $i < self::THUMB_MAX && ($fileName = $this->dbObject->fetchImgFilename()); ) {
			/*
			 * Process thumnails.
			 * $filename is not a thumbnail filename AND $filename doesn't begin with prefix tt_
			 * thus thumbnail must be created.
			 */
			if (!$info->getSiteInf()->isThumbPicThumbViewFileName($fileName) 
					&& !self::imgIsAlreadyProcessed($fileName)) {
				// Looking for thumbnail for this image.
				$fileName = $this->dbObject->resizePictureIfThereIsNotAlreadyOne($fileName, Policy::imageThumbPicThumbViewPrefix(), $info->getSiteInf()->imgThumbPicThumbViewName($fileName), Constants::IMG_THUMBPICTHUMBVIEWMAXSIZE);
			}
			if ($info->getSiteInf()->isThumbPicThumbViewFileName($fileName)) {
				$webPath = $info->getSiteInf()->getPathWebImg() . "/" . $this->dbObject->imgSubdir();
				$fullPicName = preg_replace("/^" . Policy::imageThumbPicThumbViewPrefix() . "(.*)" . Policy::imageThumbPicThumbViewSuffix() . "(\..*)/", Policy::imageFullPicThumbViewPrefix() . "$1" . Policy::imageFullPicThumbViewSuffix() . "$2", $fileName);
				$fullPicFullName = "$webPath/$fullPicName";
				$this->buffer .= self::HTML_THUMBNAIL;
				$this->replaceTemplate("/_TEMPLATE_THUMBSRC_/", "$webPath/$fileName");
				$this->replaceTemplate("/_TEMPLATE_FULLPICFULLNAME_/", $fullPicFullName);
				
				switch ($i) {
					case 0: $this->replaceTemplate("/_TEMPLATE_THUMBCLASS_/", " first"); break;
					case self::THUMB_MAX - 1: $this->replaceTemplate("/_TEMPLATE_THUMBCLASS_/", " last"); break;
					default: $this->replaceTemplate("/_TEMPLATE_THUMBCLASS_/", ""); break;
				}
				// Add sum of displayed minithumbnails.
				++$i;
				
			}
			
			/*
			 * Process full pictures.
			 * $filename is not a full picture filename AND $filename doesn't begin with prefix tf_
			 * thus fullpic must be created.
			 */
			if (!$info->getSiteInf()->isFullPicThumbViewFileName($fileName) 
					&& !self::imgIsAlreadyProcessed($fileName)) {
				// Looking for FullPic for this image.
				$fileName = $this->dbObject->resizePictureIfThereIsNotAlreadyOne($fileName, Policy::imageFullPicThumbViewPrefix(), $info->getSiteInf()->imgFullPicThumbViewName($fileName), Constants::IMG_FULLPICTHUMBVIEWMAXSIZE);
			}
			if ($info->getSiteInf()->isFullPicThumbViewFileName($fileName)) {
				// This actualy happens only for the first time. This will be the main foto.
				$this->replaceTemplate("/_TEMPLATE_FULLPICSRC_/", $info->getSiteInf()->getPathWebImg() . "/" . $this->dbObject->imgSubdir() . "/" . $fileName);
			}
		}
		$this->buffer .= self::HTML_END;

		$title = new StringEx($this->dbObject->resolveCodeShortcut($this->dbObject->title));
		$text = new StringEx($this->dbObject->resolveCodeShortcut($this->dbObject->text));
		
		// Code substitution.
		$this->replaceTemplate("/_TEMPLATE_TITLE_/",$title->firstNCharsButSaveWords(20));
		$this->replaceTemplate("/_TEMPLATE_TEXT_/", $text->firstNCharsButSaveWords(180));
		$this->replaceTemplate("/_TEMPLATE_PRICE_/", LocaleManager::price($this->dbObject->price, $this->dbObject->currency));
		
		$href = self::hrefToOffer($this->dbObject->id);
		
		$this->replaceTemplate("/_TEMPLATE_OFFERHREF_/", $href);
		$this->replaceTemplate("/_TEMPLATE_FULLPICID_/", "mainimg".$this->dbObject->id);
		
		$ifInterestedThenCheckedInput = $info->isInterestedInItem($this->dbObject->id) && @$_GET[Constants::REQ_ACTION] != Constants::REQ_ACTION_INTERESTEDIN ? 'checked="checked" ' : "";
		$this->replaceTemplate("/_TEMPLATE_CHECKBOX_/", "<input type=\"checkbox\" value=\"offer-".$this->dbObject->id."\" $ifInterestedThenCheckedInput/>");
		
		// Locale substitution.
		$cm = CodeManager::getCodeManager($info);
		$this->replaceTemplate("/_TEMPLATECODE_MORE_/", $cm->get("30009"));
		$this->replaceTemplate("/_TEMPLATECODE_PRICE_/", $cm->get("30010"));
	}
	
	/**
	 * Provides extra scalability then just HtmlObject::init
	 *
	 * @see HtmlObject::init
	 * 
	 * @param string $query - sql query
	 * @param bool $displayErrors - if display errors
	 * @param bool $availableItemsCountSetting
	 * @param bool $availablePages
	 * @param bool $availableToListSwitch
	 * @param bool $availableFooter
	 */
	public static function initWithFullQuery($query, $displayErrors = false, $availableItemsCountSetting = true, $availablePages = true, $availableToListSwitch = true, $availableFooter = true) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		$res = $info->getDBConnector()->query($query);
		
		if ($availableToListSwitch) {
			echo '
				<div class="text left">
					<a href="'.
						Common::addParamToUrl(
								$info->getSiteInf()->urlRelativeWithoutSomeVariables(array(Constants::REQ_TYPEOFVIEW => true)),
								Constants::REQ_TYPEOFVIEW, Constants::REQ_TYPEOFVIEW_LIST)
						.'">'.$cm->get("30053").'</a>
				</div>';
		}
		if ($availablePages) {			
			echo "<div class=\"offer-list-pages\">";

			// display page numbers
			for ($page = 1; $page <= self::$countOfPages; ++$page) {
				if ($page == self::$currentPage) {
					echo '
					<span>&nbsp;'.
					$page.'&nbsp;</span>';
				} else {
					echo "
					<a href=\"".Common::addParamsToUrl(self::$hrefPages, Constants::REQ_PAGE, $page)."\">$page</a>";
				}
			}
			echo "
				</div>";
		}
		if ($availablePages || $availableToListSwitch) {
			echo "
				<div class=\"cleaner\"></div>";
		}
		echo '<div id="offer-thumb-container" class="center-horizontal">';
		
		$isEmpty = true;
		while($htmlOffer = HtmlOfferThumbnail::fetchInstance($res)) {
			Logger::getLogger()->debug("processing offer: " . $htmlOffer->dbObject->id);
			try {
				$htmlOffer->processMe();
				$htmlOffer->flushMe();
				$isEmpty = false;
			} catch (Exception $e) {
				$logger->error("Cannot display offer: '".$htmlOffer->dbObject->id."' due to error: '$e'");
				if ($displayErrors) {
					Error::getError()->addErrorMessage($cm->get("30205", array($htmlOffer->dbObject->id)));
				}
			}
		}
		if ($isEmpty) {
			Error::getError()->addNoticeMessage($cm->get("30202"));
		}
		echo '	<div class="cleaner"></div>';
		if ($availableFooter) {
			self::echoFooter($availableItemsCountSetting);
		}
		echo '</div>';
	}
	
	/**
	 * Output footer
	 *
	 * @param bool $availableItemsCountSetting
	 * @param bool $jsHref - url javascript function which handles checked products
	 */
	public static function echoFooter($availableItemsCountSetting, $jsHref = "javascript: Ajax.getIdsForSelectedOffersAndAddInThumbView(this); ") {
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		echo  '
						<dl class="footer">
							<dt>';
			if (@$_GET[Constants::REQ_ACTION] == Constants::REQ_ACTION_INTERESTEDIN) {
				echo '
								<a class="light" href="javascript: Ajax.getIdsForSelectedOffersAndRemoveInThumbView(this); ">'.$cm->get("30058").'</a>
								'.$cm->get("30059").'.';
			} else {
				echo '
								<a class="light" href="'.$jsHref.'">'.$cm->get("30055").'</a>
								'.$cm->get("30056").'
								<a class="light" href="?'.Constants::REQ_ACTION.'='.Constants::REQ_ACTION_INTERESTEDIN.'" >
									'.$cm->get("30057").'
								</a>.';
			}
			echo '
							</dt>
							<dd>';
			if ($availableItemsCountSetting) {
				echo '
								'.$cm->get("10020").': 
								<select onchange="Ajax.setCountOfPagesForThumbView(this.value);" class="small" name="offer-list-defaultpagescount">';
				foreach (Constants::$SETUP_COUNTOFITEMSINTHUMBVIEW as $availableCountOfItems) {
					if ($availableCountOfItems == $info->getCountOfItemsInThumbView()) {
						echo "
									<option value=\"$availableCountOfItems\" selected=\"selected\">$availableCountOfItems</option>";
					} else {
						echo "
									<option value=\"$availableCountOfItems\">$availableCountOfItems</option>";
					}
				}
			echo '				
								</select>';
			}
			echo '
							</dd>
						</dl>';
			echo '		<div class="cleaner"></div>';
	}
	
	/**
	 * Method which should group together number of calls of HtmlObject::processMe and HtmlObject::flushMe
	 * in a cycle.
	 * @see HtmlObject::init
	 *
	 * @param bool $querySpec
	 * @param bool $displayErrors
	 * @param bool $availableItemsCountSetting
	 */
	public static function init($querySpec = null, $displayErrors = false, $availableItemsCountSetting = true) {
		$logger = Logger::getLogger();
		$info = SiteContext::getSiteContext();
		$cm = CodeManager::getCodeManager();
		
		if ($querySpec == null) {
			$querySpec = " where status = 'visible' ";
		} else {
			$querySpec .= " AND status = 'visible' ";
		}
				
		// Fetch datas for pages counting
		if ($availableItemsCountSetting) {
			self::fetchDataForPagesCounting($info->getCountOfItemsInThumbView(), $querySpec);
		}
		// Do the select
		if ($querySpec !== null) {
			$query = Constants::DB_QUERY_OFFERS_ALL . " " . $querySpec . self::$queryLimit;
		} else {
			$query = Constants::DB_QUERY_OFFERS_ALL . self::$queryLimit;
		}
		self::initWithFullQuery($query);
		
	}
}
?>